# coding=utf-8
# 全世界最帅的帅哥
from elasticsearch_dsl import connections
from flask import Flask
from flask_migrate import Migrate

from ysgg1_club_subject.comment.utils.jwt_client import jwt_manager
from ysgg1_club_subject.filter.login_filter import login_filter
from ysgg1_club_subject.error_handler import register_error_handlers
from ysgg1_club_subject.nacos_register.register_server import register_server
from ysgg1_club_subject.settings import map_config


def create_app(run_type="default"):
    app = Flask(__name__)
    # 加载配置
    app.config.from_object(map_config.get(run_type))

    # 配置日志
    from ysgg1_club_subject.comment.utils.subject_logging import create_logger
    app.logger = create_logger(app)

    # 初始化sqlalchemy
    from ysgg1_club_comment.modules import db
    db.init_app(app)

    # 蓝图
    from ysgg1_club_subject.subject_domain import subject_bp
    app.register_blueprint(subject_bp)

    # 初始化Migrate  初始化 flask init  flask db migrate flask db upgrade
    # 执行以上的命令，需要默认的Flask项目入口文件 省得麻烦就把入口文件名设置成app.py 或者wsgi.py
    # 如果实在不喜欢这俩名字
    # $env:FLASK_APP = "ysgg1_club_subject/minio_client.py:app"
    # powershell echo FLASK_APP = "你的入口文件名"  linux export FLASK_APP = "你的入口文件名"
    # $env:PYTHONPATH = "E:/Ysgg1_club"
    Migrate(app, db)

    # 注册请求钩子
    app.before_request(login_filter)

    # 连接到 Elasticsearch
    connections.create_connection(hosts=['http://121.40.187.211:9200/'])

    register_error_handlers(app)

    register_server()

    jwt_manager.init_app(app)

    return app
